<template>
  <div class="app-container">
    <h2 style="text-align: center;">发布新课程</h2>
    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="提交审核" />
    </el-steps>
    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写" />
      </el-form-item>
      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select @change="subjectLevelOneChanged" v-model="courseInfo.subjectParentId" placeholder="请选择">
          <el-option v-for="subject in oneLevelSubjectList" :key="subject.id" :label="subject.title"
            :value="subject.id" />
        </el-select>
        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="请选择">
          <el-option v-for="subject in twoLevelSubjectList" :key="subject.value" :label="subject.title"
            :value="subject.id" />
        </el-select>
      </el-form-item>
      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数" />
      </el-form-item>
      <!-- 课程简介 -->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>
      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/eduservice/oss/uploadFile?host=cover'" class="avatar-uploader">
          <img :src="courseInfo.cover">
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元" /> 元
      </el-form-item>
      {{courseInfo}}
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  const defaultForm = {
    title: '',
    subjectId: '',
    teacherId: '',
    lessonNum: '',
    description: '',
    price: 0,
    cover: 'http://eric123.oss-cn-shanghai.aliyuncs.com/2021/04/22/ea92cadd-51b1-49f6-8034-8ab857e5b6ddfile.png',
    subjectParentId: ''
  }
  import { addCourseInfo, findCourseInfoById,saveUpdateDate } from '@/api/course';
  import { getNestedTreeList } from '@/api/subject';
  import { findAllTeacher } from '@/api/teacher';
  import Tinymce from '@/components/Tinymce';
  export default {
    components: { Tinymce },
    data() {
      return {
        courseInfo: defaultForm,
        saveBtnDisabled: false, // 保存按钮是否禁用
        oneLevelSubjectList: [],//一级分类集合
        twoLevelSubjectList: [],//二级分类集合
        teacherList: [],
        //BASEAPI:process.env.BASE_API
        BASE_API: process.env.BASE_API, // 接口API地址
      }
    },
    created() {
      this.init()
    },
    watch: {
      $route(to, from) {
        this.init();
      }
    },
    methods: {
      //获取一级分类id
      getFirstLevelId() {
        getNestedTreeList().then(res => {
          this.oneLevelSubjectList = res.data.items
        }).catch(err => {
          this.$message({
            type: 'error',
            message: "失败"
          })
        })
      },
      //获取所有讲师的方法
      findAllTeacher() {
        findAllTeacher().then(res => {
          this.teacherList = res.data.item
        })
      },
      //上传封面之前调用的方法
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      //上传封面成功调用的方法
      handleAvatarSuccess(res, file) {
        this.courseInfo.cover = res.data.imageUrl
      },
      //触发change事件，给二级分类赋值
      subjectLevelOneChanged(value) {
        this.courseInfo.subjectId = ''
        for (let i = 0; i < this.oneLevelSubjectList.length; i++) {
          if (this.oneLevelSubjectList[i].id === value) {
            this.twoLevelSubjectList = this.oneLevelSubjectList[i].children
          }
        }
      },
      init() {
        if (this.$route.params && this.$route.params.id) {
          this.updateCourse()
        } else {
          this.courseInfo = { ...defaultForm }
          this.findAllTeacher()
          this.getFirstLevelId()
        }
      },
      next() {
        if (!this.courseInfo.id) {
          this.addDate()
        } else {
          this.saveDate()
        }
      },
      addDate() {
        addCourseInfo(this.courseInfo).then(res => {
          const courseId = res.data.courseId
          //路由跳转到编写课程大纲页面
          this.courseInfo = { ...defaultForm }
          this.$router.push({ path: '/course/chapter/' + courseId })
          this.$message({
            type: 'success',
            message: "课程信息添加成功"
          })
        }).catch(err => {
          this.$message({
            type: 'error',
            message: "添加失败"
          })
        })
      },
      updateCourse() {
        const id = this.$route.params.id
        this.getIdCourse(id)
      },
      //根据课程id查询信息
      getIdCourse(id) {
        findCourseInfoById(id).then(res => {
          this.courseInfo = res.data.courseInfoForm
          //查询所有的一级分类
          getNestedTreeList().then(res => {
            this.oneLevelSubjectList = res.data.items
            for (let i = 0; i < this.oneLevelSubjectList.length; i++) {
            //判断每一个id和课程所属的id是否相同
            if (this.courseInfo.subjectParentId === this.oneLevelSubjectList[i].id) {
              this.twoLevelSubjectList = this.oneLevelSubjectList[i].children
            }
          }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err.message
            })
          })

          this.findAllTeacher()
        }).catch(err => {
          this.$message({
            type: 'error',
            message: "添加失败"
          })
        })
      },
      //保存修改方法
      saveDate(){
        saveUpdateDate(this.courseInfo).then(res=>{      
          this.$message({
            type: 'success',
            message: "修改成功"
          })
          this.$router.push({ path: '/course/chapter/' + res.data.courseId })
        }).catch(err=>{
          this.$message({
            type: 'error',
            message: "修改失败"
          })
        })
      }
    }
  }
</script>

<style scoped>
  .tinymce-container {
    line-height: 29px;
  }
</style>